import VueRouter from 'vue-router'

import StudentView  from '../views/StudentView.vue'
import TeacherView  from '../views/TeacherView.vue'

// student相关组件
import StudentDetail  from '../views/student/StudentDetail.vue'
import StudentEditor from '../views/student/StudentEditor.vue'


const router =  new VueRouter({
   routes:[
    {
        path: '/student',
        component: StudentView,
        meta:{
          title: '学生管理'
        },
        children:[
            // 路由嵌套配置
            {
               path:'info',
               name: 'studentDetail',
               component: StudentDetail,
               meta:{
                title: '学生信息详情'
               }
            },
            {
                path:'edit',
                name:'studentEditor',
                component: StudentEditor,
                meta:{
                  needAuth: true,
                  permission: 'student.edit',
                  title:'编辑学生信息'  
                }
            }
        ]

    },
    {
        // 命名路由
        name:'teacherRoute',
        // 动态url
        path: '/teacher/:id',
        component:TeacherView,
        meta:{
          title: '教师管理'
        },
        //参数props传递三种写法：

        //布尔模式，只对params有效，对query无效
        // props:true

        //对象模式,但是prop只能是静态
        // props:{id:'aaabbbccc'}

        //函数模式,对query和params都有效
        props: route =>({
            id: route.params.id,
            score: route.query.score
        }),
        //独享路由守卫——前置守卫
        //非常遗憾的是，没有独享的后置路由守卫
        beforeEnter(to,from,next){
            let sTime = new Date('2022-09-06 20:00:00');
            let nowTime = new Date();
            if(nowTime >= sTime){
                next();
            }else{
                alert(`${sTime.toLocaleString()}之后才能进入`)
            }
        }
    },
   ]
})

//全局路由守卫——前置守卫
router.beforeEach((to,from,next)=>{
    
    if(to.meta.needAuth){
       if(localStorage.getItem('auth')===to.meta.permission){
        next()
       }else{
        alert(`拒绝访问，缺少权限：${to.meta.permission}`)
       }
    }else{
        next()
    }
})

//全局路由守卫——后置守卫
router.afterEach((to)=>{
    document.title=to.meta.title != null ? to.meta.title : "管理系统"
})




//暴露router对象
export default router


